/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.cn360.batch.BuildCn360ProductJob
   Module Description   :

   Date Created      : 2011/6/21
   Original Author   : jeffma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.cn360.batch;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.csvreader.CsvWriter;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.thread.batch.AbstractRunJob;
import com.yaodian100.ec.cn360.remote.RemoteCn360ProductService;
import com.yaodian100.ec.product.entity.Brand;
import com.yaodian100.ec.product.service.ProductService;

/**
 * @author jeffma
 * 
 */
public class BuildCn360ProductJob extends AbstractRunJob {

	private ProductService productService;
	private List<Map<String, Object>> products;
	private Map<String, Brand> brandMap = new HashMap<String, Brand>();

	/** default constructor */
	public BuildCn360ProductJob(ProductService productService, List<Map<String, Object>> products) {
		super("BuildCn360ProductJob");
		this.productService = productService;
		this.products = products;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.thread.batch.AbstractRunJob#execute()
	 */
	@Override
	public void execute() {
		String feedFile = ServerValue.getFrontApachePath() + "3party_ex" + File.separator + "360cn" + File.separator
				+ "yaodian100_p.csv";
		File feedFileObj = new File(feedFile);
		if (feedFileObj.exists()) {
			feedFileObj.delete();
		}
		try {
			CsvWriter writer = new CsvWriter(feedFile, ',', Charset.forName("gb2312"));
			writer.writeRecord(new String[] { "bid", "outer_id", "bc_id", "brand_name", "brand_ename", "brand_alias",
					"item_name", "item_alias", "product_code", "sale_title", "recommend_des", "item_summary", "item_des",
					"market_price", "sale_price", "main_props", "other_props", "pic_url", "item_image", "is_offergift",
					"offergift", "peoplegroup", "is_new", "has_storage", "has_invoice", "free_delivery", "cash_on_delivery",
					"quality_guarantee", "noreason_return", "reserve", "reserve_des", "has_certificate", "sale_num",
					"time_on_market", "time_on_sale", "after_service", "other_service", "source_url" });

			CommonCriteria cri = new CommonCriteria();
			List<Brand> brandList = productService.getBrandList(0, -1, cri, new String[] { "brandId" });
			for (Brand b : brandList) {
				brandMap.put(b.getBrandId(), b);
			}

			int count = 0;
			String[] data = new String[] { RemoteCn360ProductService.BID, "", "", "", "", "", "", "", "", "", "", "", "", "",
					"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };
			for (Map<String, Object> product : products) {
				if (product.get("MAIN_CATEGORY_PATH") == null) {
					logger.warn("product categpry path is null, product id:{}", product.get("PRODUCT_ID"));
					continue;
				}
				if (product.get("MAIN_CODE_LABEL") == null) {
					logger.warn("product main label/name is null, product id:{}", product.get("PRODUCT_ID"));
					continue;
				}
				if (product.get("SECOND_CODE_LABEL") == null) {
					logger.warn("product second label/name is null, product id:{}", product.get("PRODUCT_ID"));
					continue;
				}

				data[1] = product.get("PRODUCT_ID").toString();
				data[2] = product.get("MAIN_CATEGORY_PATH").toString();
				data[2] = StringUtils.split(data[2], "/")[0];

				if (product.get("PRODUCT_BRAND") != null) {
					Brand b = brandMap.get(product.get("PRODUCT_BRAND").toString());
					if (b != null) {
						brandMap.put(b.getBrandId(), b);
						data[3] = b.getBrandName();
						if (StringUtils.isBlank(data[3])) {
							data[3] = b.getBrandEname();
						}
					} else {
						// brand not found
						data[3] = " ";
					}
				} else {
					data[3] = " ";
				}
				data[6] = StringUtils.simplized(product.get("PRODUCT_NAME").toString());
				if (product.get("PROMOTE_NAME") != null) {
					data[9] = StringUtils.simplized(product.get("PROMOTE_NAME").toString()) + " " + data[6];
				} else {
					data[9] = data[6];
				}

				data[12] = productService.readFromFile(data[1], "description");
				data[12] = StringUtils.removeHTML(data[12], false);
				if (StringUtils.isBlank(data[12]) || data[12].length() < 6) {
					data[12] = productService.readFromFile(data[1], "details");
					data[12] = StringUtils.removeHTML(data[12], false);
					if (StringUtils.isBlank(data[12]) || data[12].length() < 6) {
						data[12] = "******";
					}
				}
				data[13] = product.get("LIST_PRICE").toString();
				if (data[13].indexOf(".") == -1) {
					data[13] = data[13] + ".00";
				} else if (data[13].indexOf(".") == data[13].length() - 2) {
					data[13] = data[13] + "0";
				}
				data[14] = product.get("SHELF_PRICE").toString();
				if (data[14].indexOf(".") == -1) {
					data[14] = data[14] + ".00";
				} else if (data[14].indexOf(".") == data[14].length() - 2) {
					data[14] = data[14] + "0";
				}

				Set mainProp = new HashSet(), secondProp = new HashSet();
				for (String s1 : StringUtils.split(product.get("JOIN_SPEC").toString(), ";")) {
					s1 = replace(s1);
					String[] s2 = StringUtils.split(s1, "／");
					if (s2.length > 1) {
						mainProp.add(s2[0]);
						s2[1] = replace(s2[1]);
						if (s2[1].indexOf(",") == -1) {
							secondProp.add(s2[1]);
						} else {
							secondProp.addAll(Arrays.asList(StringUtils.split(s2[1], ",")));
						}
					} else {
						mainProp.add(s2[0]);
					}
				}

				data[15] = replace(product.get("MAIN_CODE_LABEL").toString()) + ":"
						+ StringUtils.join(mainProp.toArray(), "||") + ";" + replace(product.get("SECOND_CODE_LABEL").toString())
						+ ":" + StringUtils.join(secondProp.toArray(), "||");

				// if (data[15].indexOf(":") != -1 && data[15].indexOf("||") !=
				// -1) {
				// data[15] = StringUtils.replace(data[15], "／", ":");
				// data[15] = StringUtils.replace(data[15], ",", ";");
				// } else {
				// data[15] = StringUtils.replace(data[15], ":", " ");
				// data[15] = StringUtils.replace(data[15], "||", " ");
				// data[15] = StringUtils.replace(data[15], "／", ":");
				// data[15] = StringUtils.replace(data[15], ",", ";");
				// }
				data[17] = "http://s.yaodian100.com/PImg/" + data[1].substring(0, 4) + "/" + data[1] + "/" + data[1]
						+ "_m250.jpg"; // image
				data[22] = "true";
				data[23] = "1";
				data[24] = "true";
				data[27] = "true";
				data[28] = "true";
				data[34] = DateUtil.convertDateToString(DateUtil.PATTERN_TIMESTAMP, (Date) product.get("SHELF_START_DATE"));
				data[36] = "七天可退,十五天可换";
				data[37] = "http://www.yaodian100.com/ecmall/product/product.do?productId=" + data[1] + "&hpp=360cn_sync";

				writer.writeRecord(data);
				count++;
				if (count % 800 == 0) {
					writer.flush();
				}
			}
			writer.flush();
			writer.close();
		} catch (Exception e) {
			logger.error("写档错误", e);
		}
	}

	private String replace(String value) {
		String data = StringUtils.remove(value, "1=");
		data = StringUtils.remove(data, "2=");
		data = StringUtils.replace(data, ":", "#m#");
		data = StringUtils.replace(data, ";", "#f#");
		return data;
	}
}
